package com.back.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.back.entity.Review;
import com.back.entity.Score;
import com.back.service.inte.ReviewService;
import com.back.uitls.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ReviewController {

    @Autowired
    private ReviewService reviewService;

    // 获取某个电影的评论，带分页，按时间排序
    @GetMapping("/review")
    public SaResult selectReviewByMovieId(
            @RequestParam("movie_id") int movie_id,
            @RequestParam("current") int current,
            @RequestParam("pagesize") int pagesize
    ) {
        try {
            Map<String, Object> map = reviewService.selectReviewByMovieId(movie_id, current, pagesize);

            return SaResult.data(map).setMsg("获取评论成功");

        } catch (Exception e) {
            return SaResult.error(e.getMessage());
        }
    }

    // 对某个电影添加评论
    @PostMapping("/review")
    public SaResult insertReview(
            @RequestBody Review review
    ) {
        try {
            // 检查登录状态
            try {
                StpUtil.checkLogin();
            } catch (Exception e) {
                return SaResult.error().setMsg("请先登录").setCode(401);
            }
            Integer loginId = Integer.parseInt((String) StpUtil.getLoginId());
            System.out.println(loginId);

            review.setFrom_user_id(loginId);

            reviewService.insertReview(review);
            return SaResult.ok().setMsg("评论成功");
        } catch (Exception e) {
            return SaResult.error(e.getMessage());
        }

    }

    // 对某个电影进行打分
    @PostMapping("/movie/score")
    public SaResult insertScore(
            @RequestBody Score score
    ) {
        try {
            // 检查登录状态
            try {
                StpUtil.checkLogin();
            } catch (Exception e) {
                return SaResult.error().setMsg("请先登录").setCode(401);
            }

            int loginId = Integer.parseInt((String) StpUtil.getLoginId());

            reviewService.insertScore(score.getMovie_id(), loginId, score.getScore());
            return SaResult.ok().setMsg("评分成功");
        }catch (MyException e) {
            return SaResult.error().setMsg(e.getMessage());
        }catch (Exception e) {
            return SaResult.error(e.getMessage());
        }
    }
}
